<template>
	<view>
		<view class="navbar">
			<view class="iconfont fontstyle" @click="gotoback">&#xe616;</view>
			<navigator url="/pages/recharge/recording" class="bill">账单</navigator>
		</view>
		<view class="title">
			话费充值
		</view>
		<view class="rephone">
			<view class="phonebox">
				<input class="phonestyle" @input="inputphone" @click="showDigitKeyboard=true" :value="userinfo.phone" type="text"
				 maxlength="13" placeholder="输入手机号">
				<image src="/static/image/phonenum.png" mode="aspectFill" @click="visitContacts"></image>
			</view>
			<text>{{rechargename}}</text>
		</view>
		<view class="balance">
			<navigator url="/pages/recharge/prestore" class="money">账户总额：<text class="redcolor">{{rechargemoney.prestore_balance}}</text>元</navigator>
			<view class="current">本月可使用：<text class="greencolor">{{rechargemoney.activation}}</text>元</view>
		</view>
		<view class="rechargemoney">
			<view :class="['moneyitem',tabindex==index?'hoveritem':''] " v-for="(item,index) in rechargedata.list" :key="index"
			 @click="choiceprice(index)">
				<text class="price">{{item.price}}元</text>
				<text>最低价：¥{{item.relPrice}}</text>
			</view>
		</view>
		<!--选择支付方式-->
		<view class="paymode">
			<view class="paytitle">支付方式：</view>
			<radio-group @change="radioChange" class="payentity">
				<label>
					<radio value="1" color="#378aff" :checked="paymode==1" style="transform: scale(0.8);" />账户余额
				</label>
				<label v-if="selfcoupon.length>0">
					<radio value="2" color="#378aff" :checked="paymode==2" style="transform: scale(0.8);" />优惠券
				</label>
			</radio-group>
			<view class="coupon" v-if="this.paymode==2">
				<view @click="choicecoupon(index)" :class="['order-pay',couponIndex==index?'order-pay-hover':'']" v-for="(item,index) in selfcoupon"
				 :key="index">
					<image :src="couponIndex==index?'/static/image/coupon.png':'/static/image/coupon_init.png'"></image>
					<view><text style="font-size: 18rpx;">¥</text>{{item.amount}}元</view>
				</view>
			</view>
		</view>
		<view class="comfir" @click="recharge">
			确认支付
		</view>
		<!--邀请好友进度-->
		<speed :userinfo="userinfo"></speed>
		<!-- <view @click="wifi">打开wifi</view> -->
		<!--加载遮罩-->
		<loadingpage v-if="globelloading"></loadingpage>
		<!--数字键盘-->
		<!-- 	<custom-digitKeyboard :visible.sync="showDigitKeyboard" @close="closeHandle" @confirm="confirmHandle" :max="99999999999"
		 :maxLength="11" :decimals="false" />
		</custom-digitKeyboard> -->
		<!--弹出电话本-->
		<ejectbox :visible="visible" :autoheight="autoheight">
			<scroll-view scroll-y="true" style="height: 800rpx ;">
				<view class="myphonebook" v-for="(item,index) in telbook" :key="index" @click="hoverindex=index">
					<view class="realname">{{item.displayName}}</view>
					<view :key="index" @click="selectphone(index,phoneindex)" class="phonebookitem" v-if="hoverindex===index" v-for="(phoneitem,phoneindex) in item.phoneNumbers">{{phoneitem.value}}</view>
				</view>
			</scroll-view>
		</ejectbox>
		<!--显示好友邀请-->
		<friend-invite :inviteShare="inviteShare" :inviteheight="inviteheight" :userinfo="userinfo"></friend-invite>
	</view>
</template>

<script>
	/**
	 * 充值页面
	 */
	import nativeCommon from '@/js_sdk/WH-VisitContacts/native.common';
	export default {
		data() {
			return {
				// adData:{},
				visible: false,
				autoheight: 1080,
				hoverindex: '',
				globelloading: true,
				userinfo: '',
				tabindex: 0,
				listdate: [],
				telbook: [], //电话本信息
				showDigitKeyboard: false,
				inviteShare: false,
				inviteheight: 1080, //海报高度
				shareimg: '', //分享海报
				couponIndex: 0, //卡券索引
				paymode: 1, //支付方式 默认余额支付
				rechargedata: {
					coupon: []
				}, //充值接口数据
				couponId: 0, //卡券ID
				rechargename: '',
				iscounponpage: false //页面来源为卡券进入充值

			}
		},

		onLoad(option) {
			if (option.type == "couponpage") {
				this.iscounponpage = true
				this.couponId = option.coupon_id
			}
			this.userinfo = uni.getStorageSync('user_info');
			//	console.log(this.userinfo);
			//this.userinfo.phone = this.addphoneempty(this.userinfo.phone)
			//获取充值面额
			this.redenomination()
			//记录今天是否访问过此页面
			this.$redpoint(option);
			uni.$on("closewindown", (option) => {
				this.visible = option;
				this.autoheight = 1080;

			})
			//唤起/关闭邀请好友组件
			uni.$on('invitemyfriend', (option) => {
				//console.log(111111);
				this.inviteShare = option
			})
			let sys = uni.getSystemInfoSync()
			this.inviteheight = sys.screenHeight - 260
			this.userinfo.phone = ""
		},
		computed: {
			rechargemoney() {
				return this.$common.state.userrecharge;
			},
			selfcoupon() {
				return this.$common.state.couponlist
			}
		},
		watch: {
			rechargedata() {
				this.globelloading = false
			}

		},
		methods: {
			//选择卡券
			choicecoupon(index) {
				this.couponIndex = index;
				this.couponId = this.rechargedata.coupon[index].id;
				//console.log(this.couponId)
			},
			//选择充值方式
			radioChange(e) {
				//console.log()
				this.paymode = e.detail.value;
			},
			//通讯录
			wifi() {
				plus.runtime.launchApplication({
					action: 'App-Prefs:root=WIFI'
				}, function(e) {
					console.log(JSON.stringify(e));
				});
			},
			//获取电话号码
			selectphone(bigindex, smallindex) {
				this.userinfo.phone = this.addphoneempty(this.telbook[bigindex].phoneNumbers[smallindex].value);
				this.$ShowMsg('电话薄号码已选择！')
				this.visible = false;
				this.autoheight = 1080;
			},

			confirmHandle(value) {
				//点击键盘完成的回调函数
				let phones = value.toString();
				if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(phones))) {
					this.$ShowMsg("手机号码有误，请重填");
					return;
				}
				this.userinfo.phone = this.addphoneempty(phones);
			},
			closeHandle() {
				//键盘关闭的回调函数
			},
			//选择价格
			choiceprice(index) {
				this.tabindex = index
			},
			//输入电话号码
			inputphone(e) {
				this.userinfo.phone = this.addempty(e.detail.value)
				this.rechargename = ''
			},
			//给号码加空格
			addempty(nums) {
				// if (nums.length == 3) {
				// 	let start = nums.substr(0, 3);
				// 	return start + ' ';
				// } else if (nums.length == 8) {
				// 	let start = nums.substr(0, 3);
				// 	let middle = nums.substr(4, 5);
				// 	return start + ' ' + middle + ' ';
				// }

				var value = nums;
				value = value.replace(/\s*/g, "");
				var result = [];
				for (var i = 0; i < value.length; i++) {
					if (i == 3 || i == 7) {
						result.push(" " + value.charAt(i));
					} else {
						result.push(value.charAt(i));
					}
				}

				return result.join("")
			},

			addphoneempty(nums) {
				//let phonenum = nums.replace(/\+(86)?|-*\s*/g, '')
				//先去空
				let tempnums = nums.replace(/-*\s*/g, '');
				//后匹配数字
				let phonenum = tempnums.match(/1[3-9]\d{9}/g)[0]

				let start = phonenum.substr(0, 3);
				let middle = phonenum.substr(3, 4);
				let end = phonenum.substr(7, 4);
				return start + ' ' + middle + ' ' + end;
			},

			//获取充值面额
			redenomination() {
				this.$HttRequest({
					url: '/index/rechargeList',
					param: ''
				}).then((ret) => {
					console.log(ret);
					if (ret.status === 10000) {
						this.rechargedata = ret.data;
						this.$common.state.userrecharge = {
							prestore_balance: ret.data.prestore_balance,
							activation: ret.data.activation
						}
						//设置用户话费的优惠券
						this.$common.state.couponlist = ret.data.coupon;
						//更新用户充值余额
						this.$set(this.userinfo, 'prestore_balance', ret.data.freeze);
						//优先选择优惠券并选择指定卡券
						if (this.iscounponpage) {
							this.paymode = 2
							//获取卡券的索引
							ret.data.coupon.map((item, index) => {
								if (item.id == this.couponId) {
									this.couponIndex = index
								}
							})
						} else if (ret.data.coupon.length > 0) {
							//初始化优惠券
							this.couponId = ret.data.coupon[0].id
						}
					} else {
						this.$ShowMsg(ret.message);
					}
				}).catch((error) => {
					//异常错误
					this.$ShowMsg('statusCode：' + error);
				});
			},

			recharge() {
				let insertphone = this.userinfo.phone.replace(/\s*/g, "");
				if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(insertphone))) {
					this.$ShowMsg("手机号码有误，请重填");
					return;
				}
				let rechargeparams = {
					phone: insertphone,
					num: this.rechargedata.list[this.tabindex].price,
					coupon_id: this.paymode == 2 ? this.couponId : 0,
				}
				//如果账户余额不足跳转至充值页
				if (this.paymode == 1) {
					if (this.rechargedata.prestore_balance - rechargeparams.num < 0) {
						//this.$ShowMsg('账户余额不足!');
						uni.navigateTo({
							url: '/pages/recharge/prestore'
						})
						return
					}
				}
				//提交订单
				//console.log(rechargeparams)
				this.$HttRequest({
					url: '/recharge/genOrder',
					param: rechargeparams
				}, 'POST', true).then(ret => {
					console.log(ret.data);
					if (ret.status === 10000) {
						//复制优惠券
						this.$common.state.couponlist = ret.data.coupon;
						//下单成功后处理卡券
						if (ret.data.coupon.length > 0) {
							//充值优惠券索引
							this.couponIndex = 0
							this.couponId = ret.data.coupon[this.couponIndex].id
						} else {
							//如果优惠券为空直接清空优惠券数据
							//this.rechargedata.coupon = []
							//支付方式默认为余额支付
							this.paymode = 1
						}
						//关闭当前页面跳转
						uni.navigateTo({
							url: '/pages/recharge/rechargedetail?&prestore_balance=' + this.rechargedata.prestore_balance + '&order_id=' +
								ret.data.orderId
						})
					} else {
						this.$ShowMsg(ret.message);
					}
				}).catch((error) => {
					//异常错误
					this.$ShowMsg('statusCode：' + error.errMsg);
				})
			},
			//获取通讯录
			visitContacts() {
				let _that = this
				nativeCommon.contacts.getContact(function(name, number) {
					console.log(number);
					_that.userinfo.phone = _that.addphoneempty(number)
					_that.rechargename = name
				})
			},

			gotoback() {
				uni.navigateBack({
					delta: 1,
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-image: url('/static/image/recharge_bg.png');
		background-position: left top;
		background-size: 50% 307rpx;
		background-repeat: no-repeat;
	}

	.content {
		background-color: #DBDBDB;
		padding: 10px;
	}

	.ad-view {
		background-color: #FFFFFF;
		margin-bottom: 10px;
	}

	.coupon {
		display: flex;
		width: 98%;
		flex-wrap: wrap;
		justify-content: flex-start;
		align-items: center;

		.order-pay {
			border-radius: 20rpx;
			width: 180rpx;
			height: 65rpx;
			font-size: 30rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 15rpx 20rpx;
			background-color: #E6E6E6;
			color: #515151;

			border: 1rpx solid #d3d3d3;
			box-shadow: inset 0 0 5rpx #bdbdbd;

			image {
				width: 65rpx;
				height: 65rpx;
				margin-right: 10rpx;
			}
		}

		.order-pay-hover {
			color: #fff;
			background-color: #3296FA;
			border: 1rpx solid #5fb2ff;
			box-shadow: inset 0 0 5rpx #2680fb;
		}
	}

	.paymode {
		width: 90%;
		margin: 30rpx auto;
		font-size: 28rpx;
		color: #999;
		display: flex;
		justify-content: center;
		align-items: flex-start;
		flex-direction: column;

		.paytitle {
			color: #333;
			font-weight: bold;
			font-size: 35rpx;
			margin: 20rpx 0;
		}

		.payentity {
			font-weight: bold;
			font-size: 32rpx;
			display: flex;
			justify-content: center;
			align-items: flex-start;
			flex-direction: column;

			label {
				margin: 10rpx 0;
			}
		}
	}

	.myphonebook {

		font-weight: bold;
		color: #333;
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		flex-direction: column;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #F1F1F1;
		height: auto;

		.realname {
			font-size: 35rpx;
			margin: 10rpx 0;
		}

		.phonebookitem {
			width: 100%;
			padding: 20rpx 0;
			background-color: #F8F8F8;
			margin: 10rpx 0;
			padding-left: 20rpx;
			font-size: 28rpx;
			color: #808080;
			display: flex;
			justify-content: center;
			align-items: flex-start;
			flex-direction: column;
		}
	}

	.comfir {
		width: 90%;
		height: 90rpx;
		background-color: $uni-color-primary;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
		font-size: 32rpx;
		font-weight: bold;
		margin: 30rpx auto;
		border-radius: 30rpx;
		border: 1rpx solid #5fb2ff;
		box-shadow: inset 0 0 10rpx 5rpx #2680fb;
	}

	.rechargemoney {
		width: 90%;
		margin: 10rpx auto;
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-wrap: wrap;

		.moneyitem {
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			color: #999;
			font-size: 25rpx;
			border: 1rpx solid #d7d7d7;
			width: 200rpx;
			height: 150rpx;
			border-radius: 20rpx;
			box-shadow: 0 5rpx 8rpx #dadada;
			margin-bottom: 20rpx;

			.price {
				margin-bottom: 10rpx;
				font-weight: bold;
				font-size: 35rpx;
				color: $uni-color-primary;
			}
		}

		.hoveritem {
			color: #fff;
			background-color: $uni-color-primary;
			border: 1rpx solid $uni-color-primary;
			box-shadow: 0 5rpx 8rpx $uni-color-primary;

			.price {
				color: #fff;
			}
		}
	}

	.balance {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 38rpx;
		width: 90%;
		color: #9c999d;
		margin: 30rpx auto;

		.current {
			font-size: 28rpx;

			.greencolor {
				margin: 0 5rpx;
				font-weight: bold;
				color: $uni-color-primary;
			}
		}

		.money {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;

			.redcolor {
				font-weight: bold;
				color: #FF0000;
				font-size: 38rpx;
				margin-right: 10rpx;
				font-weight: bold;
			}
		}
	}

	//充值号码
	.rephone {
		width: 90%;
		margin: 0 auto;
		padding: 35rpx 0;
		border-bottom: 1rpx solid #F1F1F1;

		.phonebox {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin: 20rpx 0;

			.phonestyle {

				width: 85%;

				font-weight: bold;
				font-size: 50rpx;
			}

			image {
				width: 50rpx;
				height: 50rpx;
			}
		}

		.phonetip {
			font-size: 35rpx;
			color: #9c999d;
		}
	}

	.title {
		width: 90%;
		display: flex;
		justify-content: flex-start;
		margin: 0rpx auto;
		font-size: 45rpx;
		color: #1e2220;
		font-weight: bold;
	}

	.navbar {

		width: 90%;
		margin: 40rpx auto;
		margin-bottom: 0px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 100rpx;
		color: #333;

		.fontstyle {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 38rpx;
			color: #333;
			transform: rotateY(180deg);
		}

		.bill {
			font-weight: bold;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 30rpx;
		}
	}
</style>
